/*
 * @Description: 
 * @Author: fhw
 * @Date: 2023-03-26 15:05:23
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil } from 'ramda';
import { TokenDto } from 'src/common/auth/constants';
import { IdDto } from 'src/common/dto/dto';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { Repository, Between } from 'typeorm';
import { GetCategoryDto, CreateCategoryDto, UpdateCategoryDto } from './dto/category.dto';
import { CategoryEntity } from './entities/category.entity';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private categoryEntityRepository: Repository<CategoryEntity>,
    private readonly jwtService: JwtService,
  ) { }
  async getCategory(params: GetCategoryDto) {
    try {
      const { categoryName, isShow, sort, createTimeStart, createTimeEnd } = params
      const where: GetCategoryDto = {
        categoryName, isShow, sort
      }
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      const data = await this.categoryEntityRepository.find({
        where: {
          ...where,
        },
        cache: true,
        order: { date: 'DESC' },
      });
      return data;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 创建游戏分类 */
  @UseFilters(new HttpExceptionFilter())
  async createCategory(body: CreateCategoryDto, headers) {
    try {
      const { categoryName, isShow, sort } = body
      const token = headers.authorization.split(' ');
      if (!isTrue(token)) {
        throwHttp('获取token失败');
      }
      const operatorBy: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
      const category = new CategoryEntity()
      category.categoryName = categoryName
      category.isShow = isShow
      category.sort = sort
      category.createById = operatorBy.userId
      const result = await this.categoryEntityRepository.manager.save(category);
      if (isTrue(result)) {
        return '问题反馈成功'
      }
      return '问题反馈失败'
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 更新游戏分类 */
  @UseFilters(new HttpExceptionFilter())
  async updateCategory(body: UpdateCategoryDto, headers) {
    try {
      const { categoryName, sort, isShow, id } = body;
      const token = headers.authorization.split(' ');
      if (!isTrue(token)) {
        throwHttp('获取token失败');
      }
      const operatorBy: TokenDto = this.jwtService.decode(token[1]) as TokenDto;
      const categoryInfo = await this.getCategoryInfo({
        id,
      });
      if (!isTrue(categoryInfo)) {
        throwHttp('游戏分类不存在');
        return;
      }
      const { affected } = await this.categoryEntityRepository
        .createQueryBuilder()
        .update(CategoryEntity)
        .set({ categoryName, sort, isShow, updateById: operatorBy.userId })
        .where('id = :id', { id })
        .execute();
      if (affected) {
        return '更新成功';
      }
      throwHttp('更新失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取游戏分类详情 */
  @UseFilters(new HttpExceptionFilter())
  async getCategoryInfo(where) {
    try {
      return await this.categoryEntityRepository.findOne({
        where,
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 删除游戏分类 */
  @UseFilters(new HttpExceptionFilter())
  async deleteCategory({ id }: IdDto) {
    try {
      const data = await this.getCategoryInfo({ id });
      if (!isTrue(data)) {
        throwHttp('游戏分类不存在');
        return;
      }
      const { affected } = await this.categoryEntityRepository
        .createQueryBuilder()
        .delete()
        .from(CategoryEntity)
        .where('id = :id', {
          id,
        })
        .execute();
      if (affected) {
        return '删除成功';
      }
      throwHttp('删除失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
